<?php
namespace Core\Controller;

use Core\Once;

class Base extends \Core\Base {

    public $needLogin;

    public $user;

    public $loginUrl = '/index';

    public $viewData = [];

    public $name;

    public $action;
    /**
     * @var \swoole_http_request
     */
    public $request;

    /**
     * @var \swoole_http_response
     */
    public $response;
    //是否终止
    public $break = false;

    public function init()
    {

    }

    public function redirect($url,$code=302)
    {
        if($url['0'] != '/' && !in_array(substr($url,0,7),['http://','https:/'])) {
            $url = '/'.$this->name.'/'.$url;
        }
        $this->response->header('Location',$url);
        $this->response->status($code);
        $this->endResponse();
    }

    public function endResponse($txt='') {
        if($this->break) {
            return;
        }
        $this->break = true;
        $this->response->end($txt);
    }

    public function render($view=null,$data = []) {
        if($this->break) {
            return;
        }
        $viewFile = '';
        if(!$view) {
            $viewFile = Once::$APP_PATH.'views/'.$this->name.'/'.$this->action.'.php';
        }else {
            if(substr($view,0,1) == '/') {
                $viewFile = Once::$APP_PATH.'views'.$view.'.php';
            }else {
                $viewFile = Once::$APP_PATH.'views/'.$this->name.'/'.$view.'.php';
            }
        }
        if(!file_exists($viewFile)) {
            return $viewFile.' not found';
        }
        if(!empty($this->viewData)) {
            extract($this->viewData);
        }
        if(!empty($data)) {
            extract($data);
        }
        ob_start();
        require $viewFile;
        return ob_get_clean();
    }

    public function responseJson($data) {
        if($this->break) {
            return;
        }
        $this->response->header('Content-type','application/json');
        $this->endResponse(json_encode($data));
    }

    public function responseView($view=null,$data = []) {
        if($this->break) {
            return;
        }
        $this->endResponse($this->render($view,$data));
    }

    public function free()
    {
        $this->break = false;
        $this->viewData = [];
    }
}
